package api

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"io"
	"myproject/backend/models"
	"myproject/backend/types"
	"myproject/backend/utils"
	"net/http"
	"strings"
	"sync"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type CustomerApi struct {
	Ctx        context.Context
	mu         sync.Mutex
	cancelFunc context.CancelFunc
	sseRunning bool
	sseContext context.Context
	db         *gorm.DB
}

func NewCustomerApi(db *gorm.DB) *CustomerApi {
	return &CustomerApi{
		mu:         sync.Mutex{},
		sseRunning: false,
		db:         db,
	}
}

func (s *CustomerApi) StopSSE() bool {
	s.mu.Lock()
	defer s.mu.Unlock()

	if !s.sseRunning {
		fmt.Println("SSE未启动")
		return false
	}
	if s.cancelFunc != nil {
		s.cancelFunc() // 触发上下文取消
	}
	s.sseRunning = false
	return true
}
func (s *CustomerApi) ConnectToSSE() {
	s.mu.Lock()
	if s.sseRunning {
		fmt.Println("SSE已连接")
		s.mu.Unlock()
		return
	}
	s.mu.Unlock()
	sseCtx, cancelFunc := context.WithCancel(s.Ctx)

	s.mu.Lock()
	s.sseRunning = true // 先设置为 true，避免重复连接
	s.cancelFunc = cancelFunc
	s.sseContext = sseCtx
	s.mu.Unlock()
	go func() {
		defer func() {
			s.mu.Lock()
			s.sseRunning = false
			if s.cancelFunc != nil {
				s.cancelFunc()
			}
			s.mu.Unlock()
			fmt.Println("SSE连接关闭")
		}()
		client := &http.Client{}
		// req, err := http.NewRequest("GET", "https://www.supore.cn/sse/sse", nil)
		//ctx context.Context, method, url string, body io.Reader
		req, err := http.NewRequestWithContext(sseCtx, "GET", "https://www.supore.cn/sse/sse", nil)
		if err != nil {
			runtime.LogError(sseCtx, fmt.Sprintf("创建SSE请求失败: %v", err))
			return
		}
		req.Header.Set("Accept", "text/event-stream")
		req.Header.Set("Cache-Control", "no-cache")
		req.Header.Set("Connection", "keep-alive")
		req.Header.Set("x-token", utils.AuthToken)
		resp, err := client.Do(req)
		if err != nil {
			fmt.Println(fmt.Sprintf("SSE连接失败: %v", err))
			runtime.EventsEmit(sseCtx, "reconnect_event", "ok")
			return
		}
		defer resp.Body.Close()

		if resp.StatusCode != http.StatusOK {
			runtime.LogError(sseCtx, fmt.Sprintf("SSE服务器返回错误状态码: %d", resp.StatusCode))
			runtime.EventsEmit(sseCtx, "reconnect_event", "ok")
			return
		}
		reader := bufio.NewReader(resp.Body)
		for {
			select {
			case <-sseCtx.Done():
				fmt.Println("SSE连接被取消")
				return
			default:
				line, err := reader.ReadBytes('\n')
				if err != nil {
					if err == io.EOF {
						runtime.LogInfo(sseCtx, "io.EOF SSE连接关闭")
					} else if errors.Is(err, context.Canceled) {
						runtime.LogInfo(sseCtx, "context.Canceled SSE连接被取消")
					} else {
						runtime.LogError(sseCtx, fmt.Sprintf("读取SSE错误: %v", err))
					}
					// 如果出现错误，则重新连接
					runtime.EventsEmit(sseCtx, "reconnect_event", "ok")
					return
				}
				fmt.Println("SSE事件:", string(line)) // 打印事件到Wails日志
				runtime.EventsEmit(sseCtx, "sse_event", strings.Trim(string(line), "\n"))
			}
		}
	}()
	fmt.Println("SSE连接启动")
}

// 获取树形客户列表
func (c *CustomerApi) GetTreeCustomerList(req types.CustomerListReq) types.CustomerListResp {
	resp := types.CustomerListResp{}
	payload := map[string]interface{}{
		"page":          req.Page,
		"pageSize":      req.PageSize,
		"customerName":  req.CustomerName,
		"customerTel":   req.CustomerTel,
		"sex":           req.Sex,
		"ageStart":      req.AgeStart,
		"ageEnd":        req.AgeEnd,
		"createAtStart": req.CreateAtStart,
		"createAtEnd":   req.CreateAtEnd,
		"vipIds":        req.VipIds,
		"customerCode":  req.CustomerCode,
		"organId":       req.OrganId,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/customer/getTreeCustomerList",
		Resp:   &resp,
		Body:   payload,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 获取客户详情
func (c *CustomerApi) GetCustomerInfoById(id int64) types.GetCustomerInfoByIdResp {
	resp := types.GetCustomerInfoByIdResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "GET",
		Suffix: "/customer/customer/GetCustomerInfoById",
		QueryParams: map[string]interface{}{
			"id": id,
		},
		Resp: &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 获取客户关系列表
func (c *CustomerApi) GetRelativesByQuery(req types.GetRelativesByQueryReq) types.CustomerRelativesForListResp {
	var res []models.Customers
	query := c.db.Model(&models.Customers{})
	limit := int(req.PageSize)
	offset := (req.Page - 1) * req.PageSize
	var total int64
	if req.CustomerName != "" {
		query = query.Where("customer_name LIKE ?", "%"+req.CustomerName+"%")
	}
	if req.CustomerTel != "" {
		query = query.Where("customer_tel LIKE ?", req.CustomerTel+"%")
	}
	query = query.Order("id desc")
	if err := query.Count(&total).Error; err != nil {
		return types.CustomerRelativesForListResp{
			Resp: types.Resp{
				Code: types.FAIL,
				Msg:  "数据库异常",
			},
		}
	}
	// 再查询分页数据
	if err := query.Offset(int(offset)).Limit(limit).Find(&res).Error; err != nil {
		return types.CustomerRelativesForListResp{
			Resp: types.Resp{
				Code: types.FAIL,
				Msg:  "数据库异常",
			},
		}
	}
	resp := types.CustomerRelativesForListResp{}
	resp.Resp = types.Resp{
		Code: types.SUCCESS,
		Msg:  "success",
	}
	list := []types.CustomerRelativesForListRespForApi{}
	for _, v := range res {
		list = append(list, types.CustomerRelativesForListRespForApi{
			Id:                   v.ID,
			Name:                 v.CustomerName,
			Phone:                v.CustomerTel,
			Sex:                  v.Sex,
			Birthday:             v.Birthday,
			OccupationName:       v.OccupationName,
			WorkEnvName:          v.WorkEnvName,
			EyeUsageDistanceName: v.EyeUsageDistanceName,
		})
	}
	data := types.CustomerRelativesForList{
		Total: total,
		List:  list,
	}
	resp.Data = data
	return resp
}

// /customer/customer/createCustomerByPc
func (c *CustomerApi) CreateCustomerByPc(req types.CreateCustomerForApi) types.CreateCustomerResp {
	if req.Id > 0 {
		var phoneCount int64
		if err := c.db.Model(&models.Customers{}).
			Where("customer_tel = ?", req.CustomerTel).
			Where("id <> ?", req.Id).
			Count(&phoneCount).Error; err != nil {
			return types.CreateCustomerResp{
				Resp: types.Resp{
					Code: types.FAIL,
					Msg:  "数据库异常",
				},
			}
		}
		if phoneCount > 0 {
			return types.CreateCustomerResp{
				Resp: types.Resp{
					Code: types.FAIL,
					Msg:  "该手机号码已经注册",
				},
			}
		}
		if err := c.db.Model(&models.Customers{}).
			Where("id = ?", req.Id).
			Updates(map[string]interface{}{
				"customer_tel":            req.CustomerTel,
				"customer_name":           req.CustomerName,
				"sex":                     req.Sex,
				"birthday":                req.Birthday,
				"head_url":                req.HeadUrl,
				"address":                 req.Address,
				"occupation_name":         req.OccupationName,
				"work_env_name":           req.WorkEnvName,
				"eye_usage_distance_name": req.EyeUsageDistanceName,
			}).Error; err != nil {
			return types.CreateCustomerResp{
				Resp: types.Resp{
					Code: types.FAIL,
					Msg:  "数据库异常",
				},
			}
		}
		resp := types.CreateCustomerResp{
			Resp: types.Resp{
				Code: types.SUCCESS,
				Msg:  "success",
			},
			Data: types.CreateCustomerRespForApi{
				Customer: types.CustomerForApi{
					Id:                   req.Id,
					CustomerName:         req.CustomerName,
					Nickname:             req.CustomerName,
					Sex:                  req.Sex,
					Birthday:             req.Birthday,
					HeadUrl:              req.HeadUrl,
					Address:              req.Address,
					OccupationName:       req.OccupationName,
					WorkEnvName:          req.WorkEnvName,
					EyeUsageDistanceName: req.EyeUsageDistanceName,
				},
			},
		}
		return resp
	}
	var customerCount int64
	if err := c.db.Model(&models.Customers{}).
		Where("customer_tel = ?", req.CustomerTel).
		Count(&customerCount).Error; err != nil {
		return types.CreateCustomerResp{
			Resp: types.Resp{
				Code: types.FAIL,
				Msg:  "数据库异常",
			},
		}
	}
	// 如果已经存在的话则
	if customerCount > 0 {
		return types.CreateCustomerResp{
			Resp: types.Resp{
				Code: types.FAIL,
				Msg:  "该手机号码已经注册",
			},
		}
	}
	customer := models.Customers{
		CustomerName:         req.CustomerName,
		CustomerTel:          req.CustomerTel,
		Sex:                  req.Sex,
		Birthday:             req.Birthday,
		HeadUrl:              req.HeadUrl,
		Address:              req.Address,
		OccupationName:       req.OccupationName,
		WorkEnvName:          req.WorkEnvName,
		EyeUsageDistanceName: req.EyeUsageDistanceName,
	}
	if err := c.db.Create(&customer).Error; err != nil {
		return types.CreateCustomerResp{
			Resp: types.Resp{
				Code: types.FAIL,
				Msg:  "数据库异常,创建失败",
			},
		}
	}
	resp := types.CreateCustomerResp{
		Resp: types.Resp{
			Code: types.SUCCESS,
		},
		Data: types.CreateCustomerRespForApi{
			Customer: types.CustomerForApi{
				CustomerName:         req.CustomerName,
				CustomerTel:          req.CustomerTel,
				Sex:                  req.Sex,
				Phone:                req.CustomerTel,
				Nickname:             req.CustomerName,
				Birthday:             req.Birthday,
				HeadUrl:              req.HeadUrl,
				Address:              req.Address,
				OccupationName:       req.OccupationName,
				WorkEnvName:          req.WorkEnvName,
				EyeUsageDistanceName: req.EyeUsageDistanceName,
			},
		},
	}
	return resp
}

// 获取工作环境
func (c *CustomerApi) ListCustomerWorkEnv() types.BaseWorkEnvResp {
	data := []types.BaseWorkEnvFor{
		{
			Id:   1,
			Name: "极低光照，适用于夜间或昏暗环境",
			Code: "WORK001",
		},
		{
			Id:   2,
			Name: "低光照，适合于相对昏暗的室内环境",
			Code: "WORK002",
		},
		{
			Id:   3,
			Name: "中等光照，适合大多数室内工作环境",
			Code: "WORK003",
		},
		{
			Id:   4,
			Name: "高光照，适用于需要较高亮度进行精细工作的场合",
			Code: "WORK004",
		},
		{
			Id:   5,
			Name: "极高光照，常见于户外晴天环境或特定的专业工作场景",
			Code: "WORK005",
		},
		{
			Id:   6,
			Name: "变化光照，在不同光照条件下频繁切换",
			Code: "WORK006",
		},
	}
	resp := types.BaseWorkEnvResp{
		Data: types.BaseWorkEnvList{
			List: data,
		},
		Resp: types.Resp{
			Code: types.SUCCESS,
			Msg:  "success",
		},
	}
	return resp
}

// 获取用眼距离
func (c *CustomerApi) ListCustomerEyeUsageDistance() types.BaseEyeUsageDistanceResp {
	resp := types.BaseEyeUsageDistanceResp{
		Resp: types.Resp{
			Code: types.SUCCESS,
			Msg:  "success",
		},
		Data: types.BaseEyeUsageDistanceList{
			List: []types.BaseEyeUsageDistance{
				{
					Id:   1,
					Name: "30m以上",
				},
				{
					Id:   2,
					Name: "10m-30m",
				},
				{
					Id:   3,
					Name: "5m-10m",
				},
				{
					Id:   4,
					Name: "2m-5m",
				},
				{
					Id:   5,
					Name: "1m-2m",
				},
				{
					Id:   6,
					Name: "0.5m-1m",
				},
				{
					Id:   7,
					Name: "0.5m以内",
				},
			},
		},
	}
	return resp
}

// 获取客户职业列表
func (c *CustomerApi) ListCustomerOccupation() types.BaseOccupationResp {
	resp := types.BaseOccupationResp{
		Resp: types.Resp{
			Code: types.SUCCESS,
			Msg:  "success",
		},
		Data: types.BaseOccupationList{
			List: []types.BaseOccupation{
				{
					Id:   1,
					Code: "OCCU001",
					Name: "学生",
				},
				{
					Id:   2,
					Code: "OCCU002",
					Name: "办公室职员/白领",
				},
				{
					Id:   3,
					Code: "OCCU003",
					Name: "教师",
				},
				{
					Id:   4,
					Code: "OCCU004",
					Name: "设计师、摄影师等视觉相关工作者",
				},
				{
					Id:   5,
					Code: "OCCU005",
					Name: "司机",
				},
				{
					Id:   6,
					Code: "OCCU006",
					Name: "警察、消防员及其他紧急服务人员",
				},
				{
					Id:   7,
					Code: "OCCU007",
					Name: "时尚从业者",
				},
				{
					Id:   8,
					Code: "OCCU008",
					Name: "医生",
				},
				{
					Id:   9,
					Code: "OCCU009",
					Name: "护士",
				},
				{
					Id:   10,
					Code: "OCCU010",
					Name: "程序员",
				},
				{
					Id:   11,
					Code: "OCCU011",
					Name: "工人",
				},
				{
					Id:   12,
					Code: "OCCU012",
					Name: "其他",
				},
			},
		},
	}
	return resp
}

// 获取客户详情
func (c *CustomerApi) GetCustomerInfoByIdReqForApi(req types.GetCustomerInfoByIdReqForApi) types.CreateCustomerResp {
	resp := types.CreateCustomerResp{}
	params := make(map[string]interface{})
	params["id"] = req.Id
	if req.OrganId != 0 {
		params["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "GET",
		Suffix: "/customer/customer/GetCustomerInfoById",
		Resp:   &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 修改客户信息
func (c *CustomerApi) UpdateCustomerById(req types.UpdateCustomerForApi) types.CreateCustomerResp {
	// 不修改客户电话
	if err := c.db.Model(&models.Customers{}).
		Where("id = ?", req.Id).
		Updates(map[string]interface{}{
			"customer_name":           req.CustomerName,
			"sex":                     req.Sex,
			"birthday":                req.Birthday,
			"head_url":                req.HeadUrl,
			"address":                 req.Address,
			"occupation_name":         req.OccupationName,
			"work_env_name":           req.WorkEnvName,
			"eye_usage_distance_name": req.EyeUsageDistanceName,
		}).Error; err != nil {
		return types.CreateCustomerResp{
			Resp: types.Resp{
				Code: types.FAIL,
				Msg:  "数据库异常",
			},
		}
	}
	resp := types.CreateCustomerResp{
		Resp: types.Resp{
			Code: types.SUCCESS,
			Msg:  "success",
		},
		Data: types.CreateCustomerRespForApi{
			Customer: types.CustomerForApi{
				Id:                   req.Id,
				CustomerName:         req.CustomerName,
				Sex:                  req.Sex,
				Birthday:             req.Birthday,
				HeadUrl:              req.HeadUrl,
				Address:              req.Address,
				OccupationName:       req.OccupationName,
				WorkEnvName:          req.WorkEnvName,
				EyeUsageDistanceName: req.EyeUsageDistanceName,
			},
		},
	}
	return resp
}

// ListCustomerChecklistInfos
// 客户检查单列表筛选
func (c *CustomerApi) ListCustomerChecklistInfos(req types.ChecklistCodeReq) types.CustomerChecklistRequestResp {
	resp := types.CustomerChecklistRequestResp{}
	params := make(map[string]interface{})
	params["page"] = req.Page
	params["size"] = req.Size
	if req.Code != "" {
		params["code"] = req.Code
	}
	if req.Phone != "" {
		params["phone"] = req.Phone
	}
	if req.CustomerName != "" {
		params["customerName"] = req.CustomerName
	}
	if req.CustomerId != 0 {
		params["customerId"] = req.CustomerId
	}
	if req.RelationId != 0 {
		params["relationId"] = req.RelationId
	}
	if req.StartDate != "" {
		params["startDate"] = req.StartDate
	}
	if req.EndDate != "" {
		params["endDate"] = req.EndDate
	}
	if req.TimeType != 0 {
		params["timeType"] = req.TimeType
	}
	if req.OrganId != 0 {
		params["organId"] = req.OrganId
	}
	if len(req.Ids) > 0 {
		params["ids"] = req.Ids
	}
	if req.CheckListId != 0 {
		params["checkListId"] = req.CheckListId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/report/checklist/ListCustomerChecklistInfos",
		Resp:        &resp,
		QueryParams: params,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 获取员工列表
func (c *CustomerApi) GetOrganizeEmployeeList(req types.GetOrganizeEmployeeListReqForApi) types.OrganizeEmployeeForListRespForApiListResp {
	resp := types.OrganizeEmployeeForListRespForApiListResp{}
	params := make(map[string]interface{})
	if req.OrganId != 0 {
		params["organId"] = req.OrganId
	}
	if req.Name != "" {
		params["name"] = req.Name
	}
	if req.PositionId != 0 {
		params["positionId"] = req.PositionId
	}
	if req.DepartmentId != 0 {
		params["departmentId"] = req.DepartmentId
	}
	if req.PhoneNumber != "" {
		params["phoneNumber"] = req.PhoneNumber
	}
	if req.Status != 0 {
		params["status"] = req.Status
	}
	if req.Page != 0 {
		params["page"] = req.Page
	}
	if req.PageSize != 0 {
		params["pageSize"] = req.PageSize
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/employee/getOrganizeEmployeeList",
		Resp:        &resp,
		QueryParams: params,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 客户信息
func (c *CustomerApi) GetUserInfo() types.UserInfoResp {
	resp := types.UserInfoResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "GET",
		Suffix: "/ras/user/getUserInfo",
		Resp:   &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 创建亲属信息
func (c *CustomerApi) CreateRelative(req types.BatchCreateCustomerRelativeReq) types.JsResp {
	resp := types.JsResp{}
	fmt.Println("CreateRelative:", req)
	body := map[string]interface{}{
		"relatives": req.Relatives,
	}
	if req.OrganId != 0 {
		body["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/relation/createRelative",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 删除亲属信息
func (c *CustomerApi) RemoveRelativeByID(req types.RemoveCustomerRelativeByIDReq) types.JsResp {
	resp := types.JsResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/relation/removeRelativeByID",
		Resp:   &resp,
		Body: map[string]any{
			"id": req.Id,
		},
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

func (c *CustomerApi) DeleteCustomerById(req types.DeleteCustomerByIdReqForApi) types.JsResp {
	resp := types.JsResp{}
	body := map[string]interface{}{
		"customerId": req.CustomerId,
	}
	if req.OrganId != 0 {
		body["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/customer/DeleteCustomerById",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

func (c *CustomerApi) GetRelativeBaseList() types.RelativeBaseForListForRespForApiListResp {
	resp := types.RelativeBaseForListForRespForApiListResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "GET",
		Suffix: "/customer/base/getRelativeBaseList",
		Resp:   &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

func (c *CustomerApi) CreateOrganizeEmployee(req types.CreateOrganizeEmployeeReq) types.JsResp {
	resp := types.JsResp{}
	body := map[string]interface{}{}
	body["certificateUrl"] = req.CertificateUrl
	body["idCard"] = req.IdCard
	body["name"] = req.Name
	body["sex"] = req.Sex
	body["phoneNumber"] = req.PhoneNumber
	body["departmentPositionList"] = req.DepartmentPositionList
	body["headUrl"] = req.HeadUrl
	body["userName"] = req.UserName
	body["organId"] = req.OrganId
	body["domValue"] = req.DomValue
	body["organClassificationId"] = req.OrganClassificationId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/employee/createOrganizeEmployee",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 修改组织机构员工信息
func (c *CustomerApi) UpdateOrganizeEmployee(req types.UpdateOrganizeEmployeeReq) types.JsResp {
	resp := types.JsResp{}
	body := map[string]interface{}{}
	body["id"] = req.Id
	body["certificateUrl"] = req.CertificateUrl
	body["idCard"] = req.IdCard
	body["name"] = req.Name
	body["sex"] = req.Sex
	body["departmentPositionList"] = req.DepartmentPositionList
	body["headUrl"] = req.HeadUrl
	body["userName"] = req.UserName
	body["organId"] = req.OrganId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/employee/updateOrganizeEmployee",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

func (c *CustomerApi) GetOrganizeEmployeeById(req types.GetOrganizeEmployeeByIdReq) types.GetOrganizeEmployeeByIdRespForApiResp {
	resp := types.GetOrganizeEmployeeByIdRespForApiResp{}
	queryParams := map[string]any{
		"id": req.Id,
	}
	if req.OrganId != 0 {
		queryParams["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/employee/getOrganizeEmployeeById",
		Resp:        &resp,
		QueryParams: queryParams,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 删除组织机构员工信息
func (c *CustomerApi) DeleteOrganizeEmployeeById(req types.DeleteOrganizeEmployeeByIdReqForApi) types.JsResp {
	resp := types.JsResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/employee/deleteOrganizeEmployeeById",
		Resp:   &resp,
		Body: map[string]any{
			"id": req.Id,
		},
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 修改员工状态
func (c *CustomerApi) ChangeEmployeeStatus(req types.ChangeEmployeeStatusReqForApi) types.JsResp {
	resp := types.JsResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/employee/changeEmployeeStatus",
		Resp:   &resp,
		Body: map[string]any{
			"id":     req.Id,
			"status": req.Status,
		},
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// @doc "获取部门树"
// @handler GetOrganizeDepartmentTree
// get /getOrganizeDepartmentTree (GetOrganizeDepartmentTreeReqForApi) returns (DepartmentTreeResp);
func (c *CustomerApi) GetOrganizeDepartmentTree(req types.GetOrganizeDepartmentTreeReqForApi) types.DepartmentTreeRespForApiResp {
	resp := types.DepartmentTreeRespForApiResp{}
	queryParams := map[string]any{
		"organId": req.OrganId,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/department/getOrganizeDepartmentTree",
		Resp:        &resp,
		QueryParams: queryParams,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// @doc "获取职位列表"
func (c *CustomerApi) GetPositionListForDepartment(req types.GetPositionListForDepartmentReqForApi) types.PositionForListRespListResp {
	resp := types.PositionForListRespListResp{}
	queryParams := map[string]any{
		"departmentId": req.DepartmentId,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/department/getPositionListForDepartment",
		Resp:        &resp,
		QueryParams: queryParams,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// @handler GetVisitCycleByCustomer
// get /getVisitCycleByCustomer (GetVisitCycleByCustomerReqForApi) returns (GetVisitCycleByCustomerRespForApi)
func (c *CustomerApi) GetVisitCycleByCustomer(req types.GetVisitCycleByCustomerReqForApi) types.GetVisitCycleByCustomerRespForApiResp {
	resp := types.GetVisitCycleByCustomerRespForApiResp{}
	queryParams := map[string]any{
		"id": req.Id,
	}
	if req.OrganId != 0 {
		queryParams["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/customer/getVisitCycleByCustomer",
		Resp:        &resp,
		QueryParams: queryParams,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// 打开和关闭回访开关
func (c *CustomerApi) ControlVisitCycleSwitch(req types.ControlVisitCycleSwitchReqForApi) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["customerId"] = req.CustomerId
	body["reminderSwitch"] = req.ReminderSwitch
	if req.OrganId != 0 {
		body["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/customer/controlVisitCycleSwitch",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// @doc "更新和创建用户回访设置"
// @handler UpdateVisitCycle
// post /updateVisitCycle (UpdateVisitCycleCycleReqForApi) returns (EmptyResp)
func (c *CustomerApi) UpdateVisitCycle(req types.UpdateVisitCycleCycleReqForApi) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["customerId"] = req.CustomerId
	body["visitCycleDays"] = req.VisitCycleDays
	body["whyVisit"] = req.WhyVisit
	if req.OrganId != 0 {
		body["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/customer/updateVisitCycle",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
		return resp
	}
	return resp
}

// @doc "获取客户列表"
// @handler GetCustomerList
// post /getCustomerList (GetCustomerListReqForApi) returns (GetCustomerListRespForApi)
func (c *CustomerApi) GetCustomerList(req types.GetCustomerListReqGetForApi) types.GetCustomerListRespForApiResp {
	resp := types.GetCustomerListRespForApiResp{}
	queryParams := map[string]any{
		"page":     req.Page,
		"pageSize": req.PageSize,
	}
	if req.OrganId != 0 {
		queryParams["organId"] = req.OrganId
	}
	if req.CustomerName != "" {
		queryParams["customerName"] = req.CustomerName
	}
	if req.CustomerTel != "" {
		queryParams["customerTel"] = req.CustomerTel
	}
	if req.Sex != 0 {
		queryParams["sex"] = req.Sex
	}
	if req.AgeStart != 0 {
		queryParams["ageStart"] = req.AgeStart
	}
	if req.AgeEnd != 0 {
		queryParams["ageEnd"] = req.AgeEnd
	}
	if req.CreateAtStart != 0 {
		queryParams["createAtStart"] = req.CreateAtStart
	}
	if req.CreateAtEnd != 0 {
		queryParams["createAtEnd"] = req.CreateAtEnd
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/customer/getCustomerList",
		Resp:        &resp,
		QueryParams: queryParams,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

// @doc("根据组织机构id查企业样式")
// @handler QueryStyleInfosByOrganId
// post /QueryStyleInfosByOrganId (OrganIdReq) returns (ListResp)
func (c *CustomerApi) QueryStyleInfosByOrganId(req types.OrganIdReq) types.StyleInfoForApiListResp {
	resp := types.StyleInfoForApiListResp{}
	body := map[string]any{
		"organId": req.OrganId,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/report/style/QueryStyleInfosByOrganId",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

// @doc("添加综合报告企业样式")
// @handler CreateZongStyleInfo
// post /CreateZongStyleInfo (StyleInfoForApi)
func (c *CustomerApi) CreateZongStyleInfo(req types.StyleInfoForApi) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["organId"] = req.OrganId
	body["headerImg"] = req.HeaderImg
	body["footerImg"] = req.FooterImg
	body["reportTitle"] = req.ReportTitle
	body["deviceSn"] = req.DeviceSn
	body["status"] = req.Status
	body["name"] = req.Name
	body["phoneNumber"] = req.PhoneNumber
	body["id"] = req.ID
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/report/style/CreateZongStyleInfo",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) ListCheckQrCodeSetting(req types.CustomCheckQrCodeSettingParams) types.CustomCheckQrCodeSettingListResp {
	resp := types.CustomCheckQrCodeSettingListResp{}
	queryParams := map[string]any{
		"page":     req.Page,
		"pageSize": req.PageSize,
	}
	queryParams["organizeId"] = req.OrganizeId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/bms/custom/listCheckQrCodeSetting",
		QueryParams: queryParams,
		Resp:        &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) UpdateCheckQrCodeSetting(req types.CustomCheckQrCodeSettingData) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["checkLogo"] = req.CheckLogo
	body["checkTitle"] = req.CheckTitle
	body["isDefault"] = req.IsDefault
	body["organizeId"] = req.OrganizeId
	if req.Id != 0 {
		body["id"] = req.Id
	}
	if req.Remark != "" {
		body["remark"] = req.Remark
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/bms/custom/updateCheckQrCodeSetting",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) AddCheckQrCodeSetting(req types.CustomCheckQrCodeSettingData) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["checkLogo"] = req.CheckLogo
	body["checkTitle"] = req.CheckTitle
	body["isDefault"] = req.IsDefault
	body["organizeId"] = req.OrganizeId
	if req.Id != 0 {
		body["id"] = req.Id
	}
	if req.Remark != "" {
		body["remark"] = req.Remark
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/bms/custom/addCheckQrCodeSetting",
		Body:   body,
		Resp:   &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) DeleteCheckQrCodeSetting(req types.CustomCheckQrCodeSettingId) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{
		"id":         req.Id,
		"organizeId": req.OrganizeId,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/bms/custom/deleteCheckQrCodeSetting",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) GetCheckOrderQrCodeInfo(req types.CustomQueryId) types.CustomCheckQrCodeSettingInfoResp {
	resp := types.CustomCheckQrCodeSettingInfoResp{}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "GET",
		Suffix: "/bms/custom/getCheckOrderQrCodeInfo",
		Resp:   &resp,
		QueryParams: map[string]any{
			"id":         req.Id,
			"organizeId": req.OrganizeId,
		},
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) CreatePreferenceInfo(req types.CreatePreferenceReq) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["word"] = req.Word
	body["typeName"] = req.TypeName
	body["organId"] = req.OrganId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/report/preference/createPreferenceInfo",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) UpdatePreferenceInfo(req types.PreferenceReq) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["id"] = req.Id
	body["word"] = req.Word
	body["typeName"] = req.TypeName
	body["organId"] = req.OrganId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/report/preference/updatePreferenceInfo",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) DeletePreferenceInfo(req types.IdReq) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{
		"id": req.Id,
	}
	body["organId"] = req.OrganId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/report/preference/deletePreferenceInfo",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) QueryPreferenceInfo(req types.IdReq) types.PreferenceResp {
	resp := types.PreferenceResp{}
	body := map[string]any{
		"id": req.Id,
	}
	body["organId"] = req.OrganId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/report/preference/QueryPreferenceInfo",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) GetPreferenceInfoList(req types.PreferenceListReq) types.PreferenceListResp {
	resp := types.PreferenceListResp{}
	queryParams := map[string]any{
		"page": req.Page,
		"size": req.Size,
	}
	if req.OrganId != 0 {
		queryParams["organId"] = req.OrganId
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/report/preference/getPreferenceInfoList",
		QueryParams: queryParams,
		Resp:        &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

// 回访记录列表
func (c *CustomerApi) GetVisitRecordList(req types.GetVisitRecordListReqForBranch) types.VisitRecordForListRespResp {
	resp := types.VisitRecordForListRespResp{}
	queryParams := map[string]any{
		"page":     req.Page,
		"pageSize": req.PageSize,
	}
	if len(req.OrganIds) != 0 {
		queryParams["organIds"] = req.OrganIds
	}
	if len(req.OrganQueries) != 0 {
		queryParams["organQueries"] = req.OrganQueries
	}
	if req.CustomerName != "" {
		queryParams["customerName"] = req.CustomerName
	}
	if req.CustomerTel != "" {
		queryParams["customerTel"] = req.CustomerTel
	}
	if req.StartTime != 0 {
		queryParams["startTime"] = req.StartTime
	}
	if req.EndTime != 0 {
		queryParams["endTime"] = req.EndTime
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method:      "GET",
		Suffix:      "/customer/visit/visitRecord/getVisitRecordList",
		QueryParams: queryParams,
		Resp:        &resp,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) CreateVisitRecord(req types.CreateVisitRecordReqForApi) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["customerId"] = req.CustomerID
	body["estimatedVisitTime"] = req.EstimatedVisitTime
	body["organId"] = req.OrganId
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/visit/visitRecord/createVisitRecord",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) ConfirmVisitRecord(req types.ConfirmVisitRecordReqForApi) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{}
	body["id"] = req.Id
	body["visitMethod"] = req.VisitMethod
	body["visitResult"] = req.VisitResult
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/visit/visitRecord/confirmVisitRecord",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) DeleteVisitRecord(req types.DeleteVisitRecordReq) types.JsResp {
	resp := types.JsResp{}
	body := map[string]any{
		"id": req.Id,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/visit/visitRecord/deleteVisitRecord",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}

func (c *CustomerApi) TodoForVisit(req types.TodoForVisitReq) types.VisitRecordForListRes {
	resp := types.VisitRecordForListRes{}
	body := map[string]any{
		"customerId": req.CustomerId,
		"visitId":    req.VisitId,
	}
	err := utils.HttpRequest(utils.HttpRequestOptions{
		Method: "POST",
		Suffix: "/customer/visit/visitRecord/todoForVisit",
		Resp:   &resp,
		Body:   body,
	})
	if err != nil {
		resp.Code = types.FAIL
		resp.Msg = err.Error()
	}
	return resp
}
